<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="indexdb.js"></script>
<script type="text/javascript">
	window.indexedDB=window.indexedDB||window.webkitIndexedDB;
	var cn,db;
	indexedDB.deleteDatabase("MyDB");
	cn=indexedDB.open("MyDB",1);
	cn.onupgradeneeded=function(e){
	  db=e.target.result;
	  var o=db.createObjectStore("MyOBJ",{keyPath:"key"});
	  o.createIndex("值","value",{unique:true});
	};
	cn.onsuccess=function(e){
	  db=e.target.result;
	  db.doTransaction=function(f){
	    var o=db.transaction("MyOBJ","readwrite");
	    o.onerror=function(){console.log("事务运行错误")};
	    f(o.objectStore("MyOBJ"));
	  };
	};
</script>
</head>
<body>
	<input type="button" value="添加数据" id="btn_add" />
<script>
//这里放置打开和初始化数据库的代码
btn_add.onclick=function(){
  db.doTransaction(function(e){
    //清空存储对象内原来的数据
    e.clear();
    //写入下列数据
    e.add({key:"对象",value:{}});
    e.add({key:"数组",value:[]});
    e.add({key:"数字",value:3.14});
    e.add({key:"布尔",value:true});
    e.add({key:"字符串",value:"次碳酸钴"});
  });
};
</script>
<input type="button" value="add主键约束" id="btn_test1" />
<input type="button" value="put主键约束" id="btn_test2" />
<input type="button" value="put唯一约束" id="btn_test3" />
<script>
//这里放置打开和初始化数据库的代码

btn_test1.onclick=function(){
  db.doTransaction(function(e){
    e.clear();
    e.add({key:"a",value:1});
    e.add({key:"a",value:2});
  });
};
btn_test2.onclick=function(){
  db.doTransaction(function(e){
    e.clear();
    e.put({key:"b",value:4});
    e.put({key:"b",value:5});
  });
};
btn_test3.onclick=function(){
  db.doTransaction(function(e){
    e.clear();
    e.put({key:"c",value:0});
    e.put({key:"d",value:0});
  });
};
</script>
<input type="button" value="测试" id="btn_test" />
<script>
//这里放置打开和初始化数据库的代码

btn_test.onclick=function(){
  db.doTransaction(function(e){
    e.clear();
    //先插入一条记录以便读取
    e.add({key:"a",value:"次碳酸钴"});
    //读取a，这个记录存在可以读取到数据
    e.get("a").onsuccess=function(e){
      var o=e.target.result;
      console.log(o);
    };
    //这个不存在，只能读取到undefined
    e.get("b").onsuccess=function(e){
      var o=e.target.result;
      console.log(o);
    };
  });
};
</script>
<input type="button" value="测试" id="btn_test" />
<script>
//这里放置打开和初始化数据库的代码

btn_test.onclick=function(){
  db.doTransaction(function(e){
    e.clear();
    //先插入几条记录
    e.add({key:"a",value:1});
    e.add({key:"b",value:2});
    e.add({key:"c",value:3});
    //输出记录条数 输出3
    e.count().onsuccess=function(e){
      console.log(e.target.result);
    };
    //删除主键为b的记录
    e.delete("b");
    //输出记录条数 由于b被删除了，剩下两条记录 输出2
    e.count().onsuccess=function(e){
      console.log(e.target.result);
    };
  });
};
</script>
</body>
</html>